package wang.lcs.pay.wx;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.wxpay.sdk.WXPay;

import wang.lcs.pay.config.WeixinConfig;
import wang.lcs.pay.util.WebUtil;
import wang.lcs.pay.wx.dto.UnifiedOrderModel;

@Controller
@RequestMapping("/wx")
public class CreateWeixinOrderController {

    @Resource
    WXPay wxPay;
    @Resource
    WeixinConfig config;

    /**
     * 公众号支付
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/jsapi")
    @ResponseBody
    public Map<String, String> createOrder(HttpServletRequest request) throws Exception {
        return this.createOrder(request, "JSAPI");
    }

    /**
     * 扫码支付
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/native")
    @ResponseBody
    public Map<String, String> nativeCreateOrder(HttpServletRequest request) throws Exception {
        return this.createOrder(request, "NATIVE");
    }

    /**
     * App 支付
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/app")
    @ResponseBody
    public Map<String, String> appCreateOrder(HttpServletRequest request) throws Exception {
        return this.createOrder(request, "APP");
    }

    /**
     * 下划线 参数
     * 
     * @return
     * @throws Exception
     * 
     */
    public Map<String, String> createOrder(HttpServletRequest request, String type) throws Exception {
        UnifiedOrderModel order = new UnifiedOrderModel(WebUtil.request2map(request));
        order.setTradeType(type);
        order.setNotifyUrl(config.getNotifyUrl());
        Map<String, String> resp = wxPay.unifiedOrder(order.getNewMap());
        // {nonce_str=Qv3ifBmLNreymzqD, code_url=weixin://wxpay/bizpayurl?pr=pvAb3yv, appid=wx0d2ea9279c85125b,
        // sign=5B851BE7527FEB942AB965DF1820B2B4, trade_type=NATIVE, return_msg=OK,
        // result_code=SUCCESS, mch_id=1503702181, return_code=SUCCESS, prepay_id=wx22165129894046316f7d95e42327771460}
        String msg = resp.get("return_msg");
        if ("FAIL".equalsIgnoreCase(resp.get("return_code")) && msg != null && msg.contains("沙箱支付")) {
            resp.put("return_help", "沙箱测试需要指定固定金额, 请关注 WXPayAssist 微信号 查看测试用例");
        }
        return resp;
    }

}